using System;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace UPA
{
    [CustomPropertyDrawer(typeof(CLIActionArgument))]
    public class ShellActionArgumentDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            property.serializedObject.Update();
            
            GUILayout.BeginHorizontal();
            var batPathProperty = property.FindPropertyRelative("batPath");
            EditorGUILayout.PropertyField(batPathProperty, new GUIContent("批处理路径"));
            if (GUILayout.Button("选择", GUILayout.ExpandWidth(false)))
            {
                var directory = string.IsNullOrWhiteSpace(batPathProperty.stringValue)
                    ? Directory.GetCurrentDirectory()
                    : batPathProperty.stringValue;
                var path = EditorUtility.OpenFilePanel("选择批处理文件", directory, "bat");
                if (path.EndsWith(".bat"))
                {
                    batPathProperty.stringValue = PathUtils.MakeRelativeTo(Directory.GetCurrentDirectory()+Path.DirectorySeparatorChar,path);
                    property.serializedObject.ApplyModifiedProperties();
                }
            }

            GUILayout.EndHorizontal();
            
            GUILayout.BeginHorizontal();
            var shellPathProperty = property.FindPropertyRelative("shellPath");
            EditorGUILayout.PropertyField(shellPathProperty, new GUIContent("类Unix Shell路径"));
            if (GUILayout.Button("选择", GUILayout.ExpandWidth(false)))
            {
                var directory = string.IsNullOrWhiteSpace(shellPathProperty.stringValue)
                    ? Directory.GetCurrentDirectory()
                    : shellPathProperty.stringValue;
                
                var path = EditorUtility.OpenFilePanel("选择Shell文件", directory, "sh");
                if (path.EndsWith(".sh"))
                {
                    shellPathProperty.stringValue = PathUtils.MakeRelativeTo(Directory.GetCurrentDirectory()+Path.DirectorySeparatorChar,path);
                    property.serializedObject.ApplyModifiedProperties();
                }
            }

            GUILayout.EndHorizontal();

            property.serializedObject.ApplyModifiedProperties();
        }
    }
}